<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:include="common/admin/common::common_head">
    <title>项目列表</title>
</head>
<style type="text/css">
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
        -webkit-appearance: none;
    }

    input[type="number"] {
        -moz-appearance: textfield;
    }

    .data-row {
        padding: 5px 0;
    }
</style>
<link rel="stylesheet" th:href="@{/admin/assets/bootstrap-select/css/bootstrap-select.css}">
<body class="cm-no-transition cm-1-navbar">
<!--后台公共侧边栏（菜单）-->
<div th:replace="common/admin/common::common_siderbar"></div>
<!--后台公共顶部-->
<div th:replace="common/admin/common::common_top"></div>
<div id="global">
    <div class="container-fluid">
        <div class="row cm-fix-height">
            <div class="col-sm-12">
                <div class="panel panel-default">
                    <div class="panel-body">
                        <h4>投资项目列表</h4>
                        <div style="margin: 10px 0;">
                            <div class="btn-group" role="group">
                                <!--<button class="btn btn-turquoise" onclick="refreshData();" type="button">
                                    <i class="fa fa-refresh"></i> 刷新
                                </button>-->
                                <button class="btn btn-turquoise" id="add_action" type="button">
                                    <i class="fa fa-plus"></i> 添加
                                </button>
                                <!--<button class="btn btn-turquoise" type="button">
                                    <i class="fa fa-trash"></i> 批量删除
                                </button>-->
                            </div>
                        </div>
                        <table class="table table-bordered table-hover">
                            <thead>
                            <tr>
                                <th>ID</th>
                                <th>项目名称</th>
                                <th>项目类型</th>
                                <th>年化利率</th>
                                <th>锁定期</th>
                                <th title="已融资的金额">已投金额</th>
                                <th>总金额</th>
                                <!--<th>开始时间</th>-->
                                <th>项目状态</th>
                                <th>还款方式</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr th:each="product : ${productList}">
                                <td th:text="${product.pid}">ID</td>
                                <td th:text="${#strings.abbreviate(product.pname,10)}">项目名称</td>
                                <td th:text="${productTypeMap.get(product.type)}">新手标</td>
                                <!--<td th:if="1 eq ${product.type}">新手标</td>
                                <td th:if="2 eq ${product.type}">推荐标</td>
                                <td th:if="3 eq ${product.type}">官方标</td>
                                <td th:if="4 eq ${product.type}">散标</td>-->
                                <td th:text="(${#numbers.formatInteger(product.rate * 100,2)} + '%')">年化利率</td>
                                <td th:text="${product.lockDateMonth} + '个月'">项目锁定期</td>
                                <td th:text="${#numbers.formatCurrency(product.haveMoney)}"
                                    th:title="'剩余可投：' + ${#numbers.formatCurrency(product.total - product.haveMoney)}">已投金额
                                </td>
                                <td th:text="${#numbers.formatCurrency(product.total)}"
                                    th:title="'剩余可投：' + ${#numbers.formatCurrency(product.total - product.haveMoney)}">总金额
                                </td>
                                <!--<td th:text="(null != product.startDate ? ${#dates.format(product.startDate,'yyyy-MM-dd HH:mm:ss')})">开始时间</td>-->
                                <td th:text="${productStatusMap.get(product.status)}">招标中</td>
                                <td th:text="${#strings.abbreviate(productRepayTypeMap.get(product.repayType),6)}"
                                    th:title="${productRepayTypeMap.get(product.repayType)}"></td>
                                <!--<td th:if="1 eq ${product.repayType}">到期还本息</td>
                                <td th:if="1 eq ${product.repayType}">到期还本息</td>
                                <td th:if="2 eq ${product.repayType}">按月付息，到期还本息</td>
                                <td th:if="3 eq ${product.repayType}">等额本息</td>-->
                                <td>
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-info get-action" th:attrappend="data-id=${product.pid}"
                                                title="查看"
                                                type="button">
                                            <i class="fa fa-fw fa-search-plus"></i>
                                        </button>
                                        <button class="btn btn-danger remove-action" th:attrappend="data-id=${product.pid},data-name=${product.pname}"
                                                title="删除"
                                                type="button">
                                            <i class="fa fa-fw fa-trash-o"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                        <div th:if="${pager.totalPage > 0}">
                            <nav class="pull-right" style="display: inline-block">
                                <ul class="pagination shadowed" style="margin:0">
                                    <li th:class="(${pager.currPage} eq 1 ? 'disabled' : '')">
                                        <a
                                                th:href="(${pager.currPage} eq 1 ? 'javascript:;' : @{/admin/product/list(currPage=${pager.currPage-1},pageSize=${pager.pageSize})})">
                                            <span><i class="fa fa-angle-left"></i></span>
                                        </a>
                                    </li>
                                    <li th:class="(${pager.currPage} eq ${i} ? 'active')" th:each="i : ${#numbers.sequence(1, pager.totalPage)}">
                                        <a
                                                th:href="(${pager.currPage} eq ${i} ? 'javascript:;' : @{/admin/product/list(currPage=${i},pageSize=${pager.pageSize})})"
                                                th:text="${i}">1</a>
                                    </li>
                                    <li th:class="(${pager.currPage} eq ${pager.totalPage} ? 'disabled')">
                                        <a
                                                th:href="(${pager.currPage} eq ${pager.totalPage} ? 'javascript:;' : @{/admin/product/list(currPage=${pager.currPage+1},pageSize=${pager.pageSize})})">
                                            <span><i class="fa fa-angle-right"></i></span>
                                        </a>
                                    </li>
                                </ul>
                            </nav>
                            <span style="clear: both"></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--模态框，bs-example-modal-lg，modal-lg-->
    <style type="text/css">
        @media (min-width: 768px) {
            .col-sm-2 {
                width: 26.66666666666666%;
            }

            .col-sm-10 {
                width: 73.33333333333334%;
            }
        }
    </style>
    <div aria-hidden="true" aria-labelledby="myModalLabel" class="modal fade" id="myModal" role="dialog" tabindex="-1">
        <div aria-hidden="true" class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h4 class="modal-title" id="myModalLabel">
                        添加投资项目
                    </h4>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" id="actionForm" style="display: none;">
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="product_pname">投资项目名称：</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <input class="form-control" id="product_pname" maxlength="30" name="pname" placeholder="请输入投资项目名称" required type="text">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="product_rate">年化利率：</label>
                            <div class="col-sm-10">
                                <select class="selectpicker" id="product_rate" name="rate">
                                    <option th:each="r : ${#numbers.sequence(productRateMin,productRateMax)}" th:text="${r} + '%'" th:value="${r} / 100">12
                                    </option>
                                </select>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="product_start_date">投资开始时间：</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <input class="form-control" id="product_start_date" name="startDateTime"
                                           placeholder="请输入投资项目开始时间"
                                           th:min="${minDate}"
                                           type="datetime-local">
                                </div>
                            </div>
                        </div>
                        <div class="form-group" id="lock_box">
                            <label class="col-sm-2 control-label" for="product_lock_date_month">资金锁定期(月)：</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <select class="selectpicker" id="product_lock_date_month" name="lockDateMonth">
                                        <option th:each="month : ${productLockDateMonth}" th:text="|${month}个月|" th:value="${month}">1个月</option>
                                    </select>
                                    <div class="input-group-btn">
                                        <button aria-label="Help" class="btn btn-default tooltip-test" data-title="锁定期间计算收益，资金不能变动" data-toggle="tooltip"
                                                type="button">
                                            <span class="glyphicon glyphicon-question-sign"></span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="product_total">投资总金额：</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <span class="input-group-addon">￥</span>
                                    <input aria-label="Amount (to the nearest dollar)" class="form-control" id="product_total"
                                           name="total" onblur="checkMax()" th:max="${productTotalMax}"
                                           th:min="${productTotalMin}"
                                           th:placeholder="'请输入' + ${#numbers.formatInteger(productTotalMin, 1)} + '~' + ${#numbers.formatInteger(productTotalMax, 1)} + '之间的金额'"
                                           type="number">
                                    <span class="input-group-addon">.00</span>
                                    <div class="input-group-btn">
                                        <button aria-label="Help" class="btn btn-default tooltip-test"
                                                data-toggle="tooltip"
                                                th:attrappend="data-title=('总金额请在' + ${#numbers.formatInteger(productTotalMin, 1)} + '~' + ${#numbers.formatInteger(productTotalMax, 1)} + '之间')"
                                                type="button">
                                            <span class="glyphicon glyphicon-question-sign"></span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label" for="product_purchase_amount">起购金额：</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <span class="input-group-addon">￥</span>
                                    <input aria-label="Amount (to the nearest dollar)" class="form-control" id="product_purchase_amount"
                                           name="purchaseAmount"
                                           placeholder="请输入起购金额"
                                           th:min="${productPurchaseAmount}" type="number">
                                    <span class="input-group-addon">.00</span>
                                    <div class="input-group-btn">
                                        <button aria-label="Help" class="btn btn-default tooltip-test"
                                                data-toggle="tooltip"
                                                th:attrappend="data-title=('起购金额请在' + ${#numbers.formatInteger(productPurchaseAmount, 1)} + '~总金额之间')"
                                                type="button">
                                            <span class="glyphicon glyphicon-question-sign"></span>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">类型：</label>
                            <div class="col-sm-10">
                                <div class="input-group">
                                    <div class="radio">
                                        <label th:each="type : ${productTypeMap}" th:if="${typeStat.index} lt 3">
                                            <input name="type" th:checked="${typeStat.first}" th:value="${type.key}" type="radio">
                                            <span th:utext="(${type.value} + '&emsp;')"></span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </form>
                    <div id="data-show">
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">项目名称：</div>
                            <div class="col-xs-9" id="pname_text_box">项目名称</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">项目类型：</div>
                            <div class="col-xs-9" id="type_text_box">0.0</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">年化利率：</div>
                            <div class="col-xs-9" id="rate_text_box">0.0</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">项目开始时间：</div>
                            <div class="col-xs-9" id="start_date_text_box">0.0</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">锁定期：</div>
                            <div class="col-xs-9" id="lock_date_month_text_box">0.0</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">起购金额：</div>
                            <div class="col-xs-9" id="purchase_amount_text_box">0.0</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">已投金额：</div>
                            <div class="col-xs-9" id="have_money_text_box">0.0</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">总金额：</div>
                            <div class="col-xs-9" id="total_text_box">0.0</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">状态：</div>
                            <div class="col-xs-9" id="status_text_box">0.0</div>
                        </div>
                        <div class="row data-row">
                            <div class="col-xs-3 text-center">还款方式：</div>
                            <div class="col-xs-9" id="repay_type_text_box">0.0</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-default" data-dismiss="modal" type="button">取消</button>
                    <button class="btn btn-primary" id="submitBtn" type="button">提交</button>
                </div>
            </div>
        </div>
    </div>

    <footer th:replace="common/admin/common::common_footer"></footer>
</div>

<script th:replace="common/admin/common::common_footer_script"></script>
<script th:src="@{/admin/assets/bootstrap-select/js/bootstrap-select.js}" type="text/javascript"></script>
<script th:src="@{/admin/assets/js/demo/popovers-tooltips.js}" type="text/javascript"></script>
<script th:src="@{/admin/assets/layer/layer.js}" type="text/javascript"></script>
<script th:src="@{/admin/assets/js/datetime.js}" type="text/javascript"></script>
<script type="text/javascript">
    document.title = '亿人宝 - 项目列表';
    let $getAction = $('.get-action'), $removeAction = $('.remove-action');
    $getAction.tooltip();
    $removeAction.tooltip();

    const add_action = 'add', get_action = 'get';
    // 项目类型
    const typesMap = {
        1: '[[${productTypeMap.get(1)}]]',
        2: '[[${productTypeMap.get(2)}]]',
        3: '[[${productTypeMap.get(3)}]]',
        4: '[[${productTypeMap.get(4)}]]'
    };
    // 状态
    const repayTypeMap = {
        1: '[[${productRepayTypeMap.get(1)}]]',
        2: '[[${productRepayTypeMap.get(2)}]]',
        3: '[[${productRepayTypeMap.get(3)}]]'
    };

    // 将对象数据显示
    function showObjectData(modal, o) {
        // 数据展示
        $('#pname_text_box').text(o.pname);
        $('#rate_text_box').text(parseInt(o.rate * 100) + '%');
        $('#start_date_text_box').text(formatDatetime(o.startDate));
        $('#lock_date_month_text_box').text(o.lockDateMonth + '个月');
        $('#purchase_amount_text_box').text(o.purchaseAmount);
        $('#total_text_box').text(o.total);
        $('#status_text_box').text(o.status === 1 ? '招标中' : (o.status === 2 ? '已满标' : ''));
        $('#type_text_box').text(typesMap[o.type]);
        $('#have_money_text_box').text(o.haveMoney);
        $('#repay_type_text_box').text(repayTypeMap[o.repayType]);
    }

    // 刷新（清空）表单数据
    function refreshForm(_form) {
        // 获取需要操作的表单对象
        let $actionForm = _form;

        let $product_pname = $actionForm.find('#product_pname');
        $product_pname.val('');
        $actionForm.find('#product_rate').selectpicker('val', [[${productRateMin}]] / 100);
        $actionForm.find('#product_start_date').val('');
        $actionForm.find('#product_purchase_amount').val('');
        $actionForm.find('#product_total').val('');
        $actionForm.find('#product_lock_date_month').selectpicker('val', [[${productLockDateMonth[0]}]]);

        // 项目类型
        let $input_types = $actionForm.find('input[name="type"]');
        $input_types.prop('checked', false);
        $input_types.eq(2).prop('checked', true);// 默认普通标单选选中

        $('.selectpicker').selectpicker('refresh');

        $product_pname.focus();
    }

    // 表单提交
    function submitForm(_form, url) {
        let loadIndex = 0;
        $.ajax(url, {
            method: 'post',
            data: _form.serializeArray(),
            dataType: 'json',
            beforeSend: function () {
                loadIndex = layer.load(1);
            },
            success: function (data) {
                if (data.code === 0) {
                    layer.msg(data.msg, {icon: 1, time: 1000}, function () {
                        location.reload();
                    });
                } else {
                    layer.msg(data.msg, {time: 1500});
                }
            },
            complete: function () {
                if (loadIndex > 0)
                    layer.close(loadIndex);
            },
            error: function () {
                layer.msg('服务器错误，请刷新重试！');
            }
        });
    }

    // 根据当前动作显示模态框
    function open_modal(_modal, action, obj) {
        let loadIndex = layer.load(1);
        // 当前模态框
        let $cache_element = _modal;

        if (add_action === action) {// 添加操作
            $cache_element.find('#myModalLabel').text('添加投资项目');

            $cache_element.find('.modal-footer').show();
            $cache_element.find('#data-show').hide();
            let $action_box = $cache_element.find('#actionForm').show();

            // 清空表单数据
            refreshForm($action_box);
        } else if (get_action === action) {// 查看操作
            $cache_element.find('#myModalLabel').text('项目【' + obj.pname + '】的详细信息');

            $cache_element.find('.modal-footer').hide();
            $cache_element.find('#actionForm').hide();
            let $action_box = $cache_element.find('#data-show').show();

            showObjectData($action_box, obj);
        }

        layer.close(loadIndex);
        $cache_element.modal('show');
    }

    // 为提交按钮添加事件
    function addEventForSubmitBtn(_modal, action, url) {
        _modal.find('#submitBtn')[0].onclick = function (event) {
            /*表单验证*/
            let $product_pname = $('#product_pname').val().trim();// 项目名称
            if ($product_pname.length < 1 || $product_pname.length > 30) {
                layer.msg('投资项目名称长度请在1~30之间。', {time: 1500});
                return false;
            }
            let $product_rate = $('#product_rate').selectpicker('val');// 项目利率

            let $product_start_date = $('#product_start_date').val();// 项目开始时间
            if ('' == $product_start_date || 0 == $product_start_date.length) {
                layer.msg('请正确选择项目的开始时间。', {time: 1500});
                return false;
            }
            let $product_lock_date = $('#product_lock_date_month').selectpicker('val');// 项目锁定期

            let purchaseAmount = [[${productPurchaseAmount}]];// 最小起购金额
            let totalMin = [[${productTotalMin}]];// 最小总金额
            let totalMax = [[${productTotalMax}]];// 最大总金额
            let $product_total = parseFloat($('#product_total').val().trim());// 投资总金额
            if (isNaN($product_total)) {
                layer.msg('请正确填写总金额！');
                return false;
            } else if ($product_total < totalMin || $product_total > totalMax) {
                layer.msg('总金额请在' + totalMin + '~' + [[${productTotalMax}]] + '之间！');
                return false;
            }
            let $purchase_amount = parseFloat($('#product_purchase_amount').val().trim());// 项目最小起购金额
            if (isNaN($purchase_amount)) {
                layer.msg('请正确填写最小起购金额！');
                return false;
            }
            if (purchaseAmount > $purchase_amount || $product_total < $purchase_amount) {
                layer.msg('起购金额请在' + purchaseAmount + '~' + $product_total + '之间。', {time: 1500});
                return false;
            }

            layer.confirm('提交后，将不能再更改信息，确定提交吗？', function () {
                submitForm(_modal.find('form'), url);
            });
            return false;
        };
    }

    // 点击添加按钮后打开模态框
    $('#add_action').click(function () {
        let $modal = $('#myModal');
        // 打开模态款
        open_modal($modal, add_action);

        // 模态框中的提交按钮，加事件
        addEventForSubmitBtn($modal, add_action, '[[@{/admin/product/save}]]');
    });

    // 查看对象信息
    $getAction.click(function () {
        let loadIndex = layer.load(1);
        let edit_id = $(this).attr('data-id');
        $.getJSON('[[@{/admin/product/}]]' + edit_id, {}, function (data) {
            layer.close(loadIndex);
            if (data.code === 0 && undefined !== data.object) {
                open_modal($('#myModal'), 'get', data.object);

                // 模态框中的提交按钮，加事件
                //addEventForSubmitBtn('edit', '[[@{/admin/product/edit}]]');
            } else {
                layer.msg(data.msg);
            }
        });
    });

    // 移除项目（删除）
    $removeAction.click(function (event) {
        let $remove_id = $(this).attr('data-id');
        let $remove_name = $(this).attr('data-name');

        let confirmIndex = layer.confirm('确定要删除该项目【' + $remove_name + '】吗？', function () {
            let loadIndex = layer.load(1);
            $.post('[[@{/admin/product/remove/}]]' + $remove_id, {}, function (data) {
                if (data.code === 0) {
                    layer.close(loadIndex);
                    layer.msg(data.msg, {time: 1500, icon: 1}, function () {
                        layer.close(confirmIndex);
                        location.reload();
                    });
                } else {
                    layer.close(loadIndex);
                    layer.msg(data.msg);
                    layer.close(confirmIndex);
                }
            })
        });
    });

    // 限制最小起购金额不大于总金额
    function checkMax() {
        let $minInput = $('#product_purchase_amount');
        let min = parseFloat($minInput.val());
        let total = parseFloat($('#product_total').val());
        if (total < min) {// 最小起购金额大于总金额时，将最小起购金额自动改成总金额
            $minInput.val(total);
        }
    }
</script>
</body>
</html>
